package com.offcn.user.controller;

import com.offcn.bean.User;
import com.offcn.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("user")
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("user-show")
    public String userShow(Model model){
        List<User> users = userService.queryUserList();

        model.addAttribute("users",users);
        return "/WEB-INF/jsp/user/userlist.jsp";
    }
    //显示登录界面
    @RequestMapping("show-login")
    public String showLogin(@ModelAttribute("flag") String flag, Model model){
        //通过flag来控制登录的提示信息
        model.addAttribute("flag",flag);
        return "/login.jsp";
    }


    //显示注册界面
    @RequestMapping("show-register")
    public String showRegister(Model model){
        model.addAttribute("user",new User());
        return "/register.jsp";
    }

    //注册信息实现
    @RequestMapping("save-register")
    public String saveRegister(@Validated User user, Errors errors){
        //注册成功，去到登录界面
        //注册失败，返回注册界面
        if(errors.hasErrors()){
            return "/register.jsp";
        }else {
            //实现注册---保存录入信息
            userService.saveUser(user);
            return "redirect:/user/show-login";
        }
    }

    //登录功能实现
    @RequestMapping("login")
    public String login(String username, String password, RedirectAttributes attributes){
        User user = userService.queryUserByNameAndPssword(username,password);
        //成功进入主页
        //失败返回登录页面，返回登录页面时提示用户名或者密码有误
        if(user != null){
            //成功
            return "redirect:/main/show-main";
        }else{
            attributes.addFlashAttribute("flag","1");
            //失败
            return "redirect:/user/show-login";
        }
    }

    @RequestMapping("/logout")
    public String logout(){
        return "redirect:/user/show-login";
    }

}
